package com.chaofan.order.controller;

import com.chaofan.order.entity.Menu;
import com.chaofan.order.entity.Order;
import com.chaofan.order.repository.MenuRepository;
import com.chaofan.order.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能：
 * 作者：chaofan
 * 日期：2025/7/7 21:52
 * 邮箱：chaofan2685@qq.com
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuRepository menuRepository;
    
    @Autowired
    private OrderRepository orderRepository;

    @PostMapping("/add")
    public Menu createMenu(@RequestBody Menu menu) {
        return menuRepository.save(menu);
    }

    @GetMapping("/list")
    public List<Menu> getAllMenus() {
        return menuRepository.findAll().stream().sorted(Comparator.comparing(Menu::getSort)).collect(Collectors.toList());
    }

    @GetMapping("/categories")
    public ResponseEntity<List<String>> getAllCategories() {
        List<String> categories = menuRepository.findAll()
                .stream()
                .map(Menu::getCategory)
                .distinct()
                .collect(Collectors.toList());
        return ResponseEntity.ok(categories);
    }

    @DeleteMapping("/delete/{id}")
    public void deleteMenu(@PathVariable String id) {
        menuRepository.deleteById(Long.valueOf(id));
    }

    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public ResponseEntity<?> uploadImage(@RequestPart("file") MultipartFile file) throws IOException {
        File uploadDir = Path.of(System.getProperty("user.home"),".OrderFood","img").toFile();
        // 创建目录（如果不存在）
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        String newFilename = timestamp + fileExtension;

        // 保存文件
        File targetFile = Paths.get(uploadDir.getAbsolutePath(), newFilename).toFile();
        file.transferTo(targetFile);

        // 返回相对路径
        return ResponseEntity.ok().body(Map.of("path", "/upload/" + newFilename));
    }

    @PostMapping("/submit-order")
    public ResponseEntity<?> submitOrder(@RequestBody Order order) {
        order.setCreateTime(LocalDateTime.now());
        Order savedOrder = orderRepository.save(order);
        return ResponseEntity.ok().body(Map.of("success", true, "orderId", savedOrder.getId()));
    }
}